package com.cb.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cb.common.R;
import com.cb.entity.User;
import com.cb.service.UserService;
import com.cb.utils.MailUtils;
import com.cb.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) throws Exception {
        //获取手机号
        String phone = user.getPhone();
        if(!StringUtils.isEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //qq邮箱发送验证码
            MailUtils.sendTestMail(phone,code);

            //需要将生成的验证码保存到Session
            //session.setAttribute(phone,code);

            //需要将生成的验证码保存到redis
            redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);

            return R.success("邮箱验证码短信发送成功！");
        }
        return R.error("邮箱验证码短信发送失败！");
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        log.info("map:{}", map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();

        //从Session中获取保存的验证码
        //String codeInSession= (String) session.getAttribute(phone);

        //从redis中获取保存的验证码
        String codeInSession=(String)redisTemplate.opsForValue().get(phone);

        //进行验证码比对（页面提交的验证码和Session中保存的验证码比对）
        if(codeInSession!=null && codeInSession.equals(code)){
            //如果能够比对成功，说明登录成功
            User user = userService.login(phone);
            session.setAttribute("user",user.getId());
            //如果用户登录成功则删除Redis中缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登陆失败！");
    }

    /**
     * 用户退出
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request){
        //清理Session中保存的当前用户登录的id
        request.getSession().removeAttribute("user");
        return R.success("退出成功！");
    }

}
